package org.dim.oa.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dim.oa.mapper.UserMapper;
import org.dim.oa.po.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 根据用户名获取数据库该用户信息，spring security在登录时自动调用
 * WebSecurityConfigurerAdapter会拿这里的User里的password与用户输入的对比验证
 *
 * 安全数据库dao类，相当于数据库域
 * 把它当成spring security的用户信息的内存库
 */
@Service
public  class DbUserInfoService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public SessionUser loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
       
        //123456 自定义MD5加密后=e10adc3949ba59abbe56e057f20f883e
        //密码可填这个,也可以用spring security的password盐加密
        //其实应该从前端获取123455，然后passwordEncoder加密，存到库里，然后从库里取出密文
        QueryWrapper<UserEntity> objectQueryWrapper = new QueryWrapper<>();
        UserEntity dbUser = userMapper.selectOne(objectQueryWrapper.eq("user_name", s));
        if (dbUser==null){
            throw new UsernameNotFoundException(String.format("No user found with userName."));
        }
        String roleName = dbUser.getRoleName();
        GrantedAuthority au = new SimpleGrantedAuthority(roleName);
        list.add(au);
        SessionUser sessionUser = new SessionUser(s,dbUser.getPassword(),list);
        sessionUser.setAvatar(dbUser.getAvatar());
        sessionUser.setId(dbUser.getId());
        sessionUser.setRemark(dbUser.getRemark());
        sessionUser.setRoleName(dbUser.getRoleName());
        System.out.println(sessionUser);
        return sessionUser;
    }
}